package pro.lepers.portfolio.view.contents.portfolio.content {
	import fr.digitas.flowearth.command.Batcher;
	import fr.digitas.flowearth.command.IBatchable;
	import fr.digitas.flowearth.core.IIterator;
	import fr.digitas.flowearth.net.BatchLoaderItem;

	import pro.lepers.portfolio.view.contents.portfolio.data.contents.AbstractContentData;
	import pro.lepers.portfolio.view.contents.portfolio.data.contents.ImagesContentData;

	import flash.display.Bitmap;
	import flash.events.Event;
	import flash.net.URLRequest;

	/**
	 * @author Pierre Lepers
	 */
	public class ImageContent extends ThumbContent {
		
		public function ImageContent( pcData : AbstractContentData  ) {
			super( pcData );
			_pictures = new Vector.<Bitmap>();
		}

		
		override public function dispose () : void {
			for (var i : int = 0; i < _pictures.length; i++) {
				_pictures[i].bitmapData.dispose();
				_pictures[i] = null;
			}
			_pictures = null;
			super.dispose( );
		}

		override public function getLoadables() : IBatchable {
			var b : Batcher = new Batcher();
			
			
			
			var iter : IIterator = imageData.getImagesUrl();
			var url : String;
			var req : URLRequest;
			var item : BatchLoaderItem;
			while( iter.hasNext() ) {
				url	= iter.next() as String;
				req = new URLRequest( url );
				item = new BatchLoaderItem( req );
				item.addEventListener( Event.COMPLETE , onItemComplete );
				b.addItem( item );
			}
			
			return b;
		}

		override public function setSize(w : int, h : int) : void {
			super.setSize( w , h );
			
			if( _pictures.length > 0 ) {
				_pictures[ 0 ].width = _width;
				_pictures[ 0 ].height = _height;
			}
		}

		private function onItemComplete(event : Event) : void {
			var item : BatchLoaderItem = event.currentTarget as BatchLoaderItem;
			item.removeEventListener( Event.COMPLETE , onItemComplete );
			
			var b : Bitmap = item.loader.content as Bitmap;
			_pictures.push( b );
			b.smoothing = _highQuality;
			
			if( _pictures.length == 1 ) 
				addChild( _pictures[ 0 ] );
				
			_pictures[ 0 ].width = _width;
			_pictures[ 0 ].height = _height;
		}

		private function get imageData() : ImagesContentData {
			return _contentData as ImagesContentData;
		}

		
		override public function set highQuality(highQuality : Boolean) : void {
			super.highQuality = highQuality;
			
			for each (var b : Bitmap in _pictures ) {
				b.smoothing = highQuality;
			}
		}

		private var _pictures : Vector.<Bitmap>;
	}
}
